'''
This example writes a list of players with guid with the ranking scores


'''

from tremapi import TremListener
from numpy import *

class TremRank(TremListener):
	def __init__(self):
		self.guids={}
		#self.matrix=[]
		self.ShutdownGame()
		self.pos2guid=[]
		self.guid2name={}
		self.killdeads=[]
		self.elo=[]
		
		self.initgame=False
	
	def say(self, msg):
		pass
		
	def CalculateTeamElo(self, t, time):
		
		
		count=0
		elo=0
		for g in self.player_guids.keys():
			if self.player_teams[g]==t:
				guid=self._getGuidBySlot(g)
				if guid:
					elo+=self.elo[self._getIndexByGuid(self._getGuidBySlot(g))]
				else:
					elo+=1500
				count+=1
		if count==0:
			self.teamelo[t]=0
		else:
			self.teamelo[t]=elo/count
		self.numplayers[t]=count
			
			
	def ClientTeam(self, msg):
		''' args: msg.textmsg '''
		
		cmd=msg.textmsg.split(' ')
		#print cmd
		name=msg.name
		slot=-1
		for n in self.player_names.keys():
			if name==self.player_names[n]:
				slot=n
		
		if slot==-1:
			print "Player no encontrado! '%s'" % (name)
			print "mensaje completo: %s" % (msg.textmsg)
			return
			#print self.player_names
		if cmd[0]=='left':
			team=0 #spector
		else:
			if cmd[2]=='aliens.':
				team=1
			else:
				team=2
			
			
		self.player_teams[slot]=team
		
		self.CalculateTeamElo(1,msg.time)
		self.CalculateTeamElo(2,msg.time)
		
		
	def ClientConnect(self, msg):
		self.player_names[msg.slot]=msg.name
		self.player_guids[msg.slot]=msg.guid
		self.player_teams[msg.slot]=0
		self.player_time[msg.slot]=0
		self.player_connected[msg.slot]=msg.time
		
		self._addGuid(msg.guid)
		if not self.guid2name.has_key(msg.guid):
			self.guid2name[msg.guid]=[]
		name=unformat(msg.name)
		if not name in self.guid2name[msg.guid]:
			self.guid2name[msg.guid].append(name)
		
		
	def _getGuidBySlot(self, s):
		if(self.player_guids.has_key(s) and
			self.player_guids[s]!='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'):
				return self.player_guids[s]
		else:
			return None
			
	def _addGuid(self, guid):
		if(not self.guids.has_key(guid)):
				p=len(self.guids)
				self.pos2guid.append(0)
				self.guids[guid]=p
				self.pos2guid[p]=guid
				self.killdeads.append([0,0])
				self.elo.append(1500.0)
				

		
	def _getIndexByGuid(self, guid):
		return self.guids[guid]
		
	def KillSingle(self, m):
		
		#print ("%d, %d, %d - %s" % (m.slot, m.victim, m.weapon, m.textmsg))
		s=self._getGuidBySlot(m.slot)
		v=self._getGuidBySlot(m.victim)
		if s!=None and v!=None and s!=v:
			#print ("%s => %s" % (v,s))
			s=self._getIndexByGuid(s)
			v=self._getIndexByGuid(v)
			self.killdeads[s][0]+=1
			self.killdeads[v][1]+=1
			
			#if self.killdeads[s][1]!=0 and self.killdeads[v][1]!=0:
			#	rs=self.killdeads[s][0]/self.killdeads[s][1]
			#	rv=self.killdeads[v][0]/self.killdeads[v][1]
			
			
			es=1/(1+10**((self.elo[v]-self.elo[s])/400)) #0.1+abs(self.elo[v]-self.elo[s])*32
			ev=1/(1+10**((self.elo[s]-self.elo[v])/400))
			#Ev=1/(1+10^((self.elo[s]-self.elo[v])/400))
		
			self.elo[s]+=32*(1-es)
			self.elo[v]+=32*(-ev)
			#if(not self.matrix[v].has_key(s)):
			#	self.matrix[v][s]=1
			#else:
			#	self.matrix[v][s]+=1
	
	def Kill(self, m):
		return
		if not self.initgame:
			return
		#print ("%d, %d, %d - %s" % (m.slot, m.victim, m.weapon, m.textmsg))
		s=self._getGuidBySlot(m.slot)
		v=self._getGuidBySlot(m.victim)
		
		
		if s!=None and v!=None and s!=v:
			steam=self.player_teams[m.slot]
			vteam=self.player_teams[m.victim]
			if(self.numplayers[steam]==0 or self.numplayers[vteam]==0):
				return
			#print ("%s => %s" % (v,s))
			
			s=self._getIndexByGuid(s)
			v=self._getIndexByGuid(v)
			
			#if self.killdeads[s][1]!=0 and self.killdeads[v][1]!=0:
			#	rs=self.killdeads[s][0]/self.killdeads[s][1]
			#	rv=self.killdeads[v][0]/self.killdeads[v][1]
			
			
			es=1/(1+10**((self.teamelo[vteam]-self.teamelo[steam])/400)) #0.1+abs(self.elo[v]-self.elo[s])*32
			ev=1/(1+10**((self.teamelo[steam]-self.teamelo[vteam])/400))
			#Ev=1/(1+10^((self.elo[s]-self.elo[v])/400))
		
			elos=32*(1-es)
			elov=32*(-ev)
			
			for g in self.player_guids.keys():
				if self.player_teams[g]==steam:
					guid=self._getGuidBySlot(g)
					if guid:
						#print self.numplayers[steam]
						self.elo[self._getIndexByGuid(guid)]+=elos/self.numplayers[steam]
						
			for g in self.player_guids.keys():
				if self.player_teams[g]==vteam:
					guid=self._getGuidBySlot(g)
					if guid:
						self.elo[self._getIndexByGuid(guid)]+=elov/self.numplayers[vteam]

		
	def ClientDisconnect(self, m):
		if(self.player_names.has_key(m.slot)):
			del self.player_names[m.slot]
			del self.player_guids[m.slot]
			del self.player_teams[m.slot]
			
			
		self.CalculateTeamElo()
		
	def InitGame(self, msg):
		self.initgame=True
		
		
	def Exit(self, msg):
		pass
			
	def ShutdownGame(self, msg=None):
		self.player_teams={}
		self.numplayers=[0,0,0]
		self.player_names={}
		self.player_guids={}
		self.teamelo=[1500,1500,1500]		
		self.hteamelo=[[1500],[1500],[1500]]
		self.hlast=0
			
	def ClientRename(self, msg):
		#print "%d) %s => %s" % (msg.slot, msg.oldname, msg.name)
		self.player_names[msg.slot]=msg.name
		
import os
from tremapi import TremParserLog
#from tremrank import TremRank
 
def unformat(s):
	o='';
	i=0
	while i<len(s):
		if s[i]=='^':
			i+=2
		else:
			o+=s[i]
			i+=1
	return o
	
tp=TremParserLog("games.log")
tremrank=TremRank()
tp.addListener(tremrank)
tp.run()

#print ("Total de guids: %d\n" % len(matrix))
#print ("Diagrama");
#print (matrix)
#print ("Ranking:\n")

#m=[list(range(1,len(matrix))),]
#for i in range(len(matrix)):
#	m.append([])
#	for j in matrix[i]:
#		m[i+1].append(j+1)
#	m[i+1].append(0)
deads=[]
totaldeads=0
for i in range(len(tremrank.killdeads)):
	#tremrank.killdeads[i][0]+=1.0
	#tremrank.killdeads[i][1]+=1.0
	if(tremrank.killdeads[i][1]>10):
		deads.append(tremrank.killdeads[i][0])
	else:
		deads.append(0)
		
	if tremrank.killdeads[i][0]>totaldeads:
			totaldeads=tremrank.killdeads[i][0]
	#totaldeads+=tremrank.killdeads[i][0]

e=1
#deads=array(deads)
#deads/=deads.max()
#deads*=e
#deads+=1-e
#print deads

rank=array(tremrank.elo, float32)
srank=(-1*rank).argsort()
	
print ("[table]")
print ("[tr][td]Pos[/td][td]k/f(ratio)[/td][td]ELO[/td][td]names[/td][/tr]")
for j in range(len(rank)):
	i=srank[j]
	guid=tremrank.pos2guid[i]
	
	vrank=0
	#for v in matrix[i]:
	#	vrank+=rank[v]
	#vrank/=len(matrix[i])
	
	if tremrank.killdeads[i][1]==0:
		r="INF"
	else:
		r="%s%%" % (100*tremrank.killdeads[i][0]/tremrank.killdeads[i][1])
	print ("[tr][td]%-3d[/td][td]%d[/td][td]%d/%d(%s)[/td][td]%s[/td][/tr]" % (j+1, rank[i], tremrank.killdeads[i][0], tremrank.killdeads[i][1], r,', '.join(tremrank.guid2name[guid])))

print ("[/table]")
